// api/src/controllers/recommendation.js
import {
  getPersonalizedRecommendations as getRecommendationsFromService,
  getSimilarRecommendations as getSimilarFromService,
  saveUserPreferences,
} from "../utils/recommendationClient";
import User from "../models/user";
import jwt from "jsonwebtoken";
import config from "../../config";

/**
 * 获取个性化推荐
 */
export const getRecommendations = async (req, res) => {
  try {
    const userId = req.userId.toString();
    const { count = 10 } = req.query;

    // 查询用户是否已完成冷启动
    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ error: "用户不存在" });
    }

    if (!user.onboardingCompleted) {
      return res.json({
        recommendations: [],
        needsOnboarding: true,
      });
    }

    const recommendations = await getRecommendationsFromService(
      userId,
      parseInt(count, 10)
    );

    return res.json(recommendations);
  } catch (error) {
    console.error("获取推荐失败:", error);
    return res.status(500).json({ error: "获取推荐失败" });
  }
};

/**
 * 获取相似资源推荐
 */
export const getSimilarRecommendations = async (req, res) => {
  try {
    const { infoHash } = req.params;
    const { count = 6 } = req.query;
    const userId = req.userId.toString();

    const recommendations = await getSimilarFromService(
      infoHash,
      userId,
      parseInt(count, 10)
    );

    return res.json(recommendations);
  } catch (error) {
    console.error("获取相似推荐失败:", error);
    return res.status(500).json({ error: "获取相似推荐失败" });
  }
};

/**
 * 用户偏好设置/冷启动
 */
export const onboardUser = async (req, res) => {
  try {
    const userId = req.userId.toString();
    const { preferences } = req.body;

    if (!preferences) {
      console.error("偏好设置为空");
      return res.status(400).json({ error: "偏好设置不能为空" });
    }

    console.log("开始保存用户偏好:", { userId, preferences });

    try {
      // 保存偏好到推荐系统
      await saveUserPreferences(userId, preferences);
      console.log("推荐系统偏好保存成功");
    } catch (error) {
      console.error("推荐系统偏好保存失败:", error);
      // 继续执行，因为数据库更新仍然可能成功
    }

    try {
      // 更新用户完成冷启动状态
      const updatedUser = await User.findByIdAndUpdate(
        userId,
        {
          onboardingCompleted: true,
          preferences,
        },
        { new: true }
      );

      if (!updatedUser) {
        console.error("用户不存在:", userId);
        return res.status(404).json({ error: "用户不存在" });
      }

      console.log("用户偏好更新成功");
    } catch (error) {
      console.error("数据库更新失败:", error);
      return res.status(500).json({ error: "数据库更新失败" });
    }

    try {
      // 获取基于偏好的推荐
      const recommendations = await getRecommendationsFromService(userId, 10);
      console.log("获取推荐成功");
      console.log(recommendations);

      return res.json({
        success: true,
        recommendations: recommendations.recommendations || [],
      });
    } catch (error) {
      console.error("获取推荐失败:", error);
      // 即使获取推荐失败，也返回成功，因为偏好已经保存
      return res.json({
        success: true,
        recommendations: [],
      });
    }
  } catch (error) {
    console.error("保存用户偏好失败:", error);
    return res.status(500).json({
      error: "保存偏好设置失败",
      details: error.message,
    });
  }
};
